package com.webserver.servlet;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;


/**
 * 用来生成展现所有用户的动态页面
 */
public class ShowAllUserServlet extends HttpServlet{

    public void service(HttpRequest request,HttpResponse response){
        System.out.println("开始生成动态页面……");
        /*
        生成一个动态页面
         */
        try (
                RandomAccessFile raf=new RandomAccessFile("user.dat","r");
        ){
//            PrintWriter pw=new PrintWriter("userList.html","utf-8");
            PrintWriter pw=response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"3\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("<td>操作</td>");
            pw.println("</tr>");

            for (int i = 0; i <raf.length()/100 ; i++) {

                byte[]data=new byte[32];
                raf.read(data);
                String user=new String(data,"utf-8").trim();
                raf.read(data);
                String password=new String(data,"utf-8").trim();
                raf.read(data);
                String nickname=new String(data,"utf-8").trim();
                int age=raf.readInt();
                pw.println("<tr>");
                pw.println("<td>"+user+"</td>");
                pw.println("<td>"+password+"</td>");
                pw.println("<td>"+nickname+"</td>");
                pw.println("<td>"+age+"</td>");
                pw.println("<td><a href=\"./ToUpdateServlet?username="+user+"\">修改</a></td>");
                pw.println("</tr>");
            }
            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
            /*
            设置Content-Type，告知浏览器正文是什么
             */
            response.setContentType("text/html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("动态页面生成成功！！！");
    }
}
